// 范围内输出文字
export const drawText = (text, x, y, w, cxt, lineheight=20) => {
  let chr = text.split(""); // 将字符串分开
  let temp = ""; //储存当前行的字符串
  let row = [];// 存储行的数组

  for (let i = 0, _let = chr.length; i < _let; i++) {
    if (cxt.measureText(temp).width < w) {
      ;
    } else {
      row.push(temp);
      temp = "";
    }
    temp += chr[i];
  }
  row.push(temp);
  // console.log(cxt.measureText(row[0]).width, w);

  for (var b = 0; b < row.length; b++) {
    cxt.fillText(row[b], x, y + (b + 1) * lineheight);
  }
  // cxt.draw();
}

// 绘制圆角矩形
export const roundRect = function (x, y, w, h, r) {
  var min_size = Math.min(w, h);
  if (r > min_size / 2) r = min_size / 2;
  // 开始绘制
  this.beginPath();
  this.moveTo(x + r, y);
  this.arcTo(x + w, y, x + w, y + h, r);
  this.arcTo(x + w, y + h, x, y + h, r);
  this.arcTo(x, y + h, x, y, r);
  this.arcTo(x, y, x + w, y, r);
  this.closePath();
  return this;
}

// 辅助函数
export const Rect = function (x, y, w, h) {
  return { x: x, y: y, width: w, height: h };
}
// 绘制圆角矩形路径
export const drawUsingArc = function (rect, r, cxt) {
  cxt.beginPath();
  cxt.moveTo(rect.x + r, rect.y);
  cxt.lineTo(rect.x + rect.width - r, rect.y);
  cxt.arc(rect.x + rect.width - r, rect.y + r, r, Math.PI / 180 * 270, 0, false);
  cxt.lineTo(rect.x + rect.width, rect.y + rect.height - r);
  cxt.arc(rect.x + rect.width - r, rect.y + rect.height - r, r, 0, Math.PI / 180 * 90, 0, false);
  cxt.lineTo(rect.x + r, rect.y + rect.height);
  cxt.arc(rect.x + r, rect.y + rect.height - r, r, Math.PI / 180 * 90, Math.PI / 180 * 180, false);
  cxt.lineTo(rect.x, rect.y + r);
  cxt.arc(rect.x + r, rect.y + r, r, Math.PI / 180 * 180, Math.PI / 180 * 270, false);
  // cxt.closePath();
}

// save
export const save_return = function ( cxt, callback) {
  cxt.save();
  callback();
  cxt.restore();
}
